<?php
// Module Body

function hd_quota_check(&$data) {
	global $cfg;
	$mysqldbpath="/var/lib/mysql/";

	// Start Group(Domain) HD Quota check
	$dbp = mysql_query("SELECT id,owner FROM domains WHERE type='domain'");
	if ($dbp != FALSE && mysql_num_rows($dbp) > 0) {
		while ($data = mysql_fetch_array($dbp)) {

			unset($hometotal);
			unset($quotatotal);

			if (strlen($data['owner']) < 10 ) {

				// neccessary to allow linux to update group quota files
				exec($cfg['prog']['quota']." -g g".$data['id'] ,$quota);

				// calc disk space used by domain in /home/domainname/
				unset($tmpquota);
				if (is_dir($cfg['webdir']."/".$data['id']."/")) {
					exec($cfg['prog']['du']." -s ".$cfg['webdir']."/".$data['id']."/" ,$tmpquota);
					$tmpquota = explode(" ",trim(eregi_replace("[[:space:]]+", " ", $tmpquota[0])));
				}
				$hometotal = $tmpquota[0];
				webcp_log(3,0,'quota',$cfg['webdir']."/".$data['id']."/ size = ".$hometotal,0,$echo);

				// Start User HD Quota check
				$dbp_user = mysql_query("SELECT username FROM users WHERE id='".$data['id']."' AND type != 'demo'");
				while ($dbp_user != FALSE && mysql_num_rows($dbp_user) > 0 && $data_user = mysql_fetch_array($dbp_user)) {

					unset($mysqlquota);
					unset($userquota);
					unset($usertotal);
					unset($mailquota);
					unset($imapquota);

					$unique = get_property('unix user', $data['id'], $data_user['username']);

					// get user disk quota
					exec($cfg['prog']['quota']." -u ".$unique, $userquota);
					if (!$userquota[3]) {
						$num = 2;
					} else {
						$num = 3;
					}
					$userquota = explode(" ",trim(ereg_replace("[[:space:]]+", " ", $userquota[$num])));

					// get mysql database disk usage
					mysql_select_db('mysql');
					$dbp_mysql = mysql_query("SELECT Db FROM db where User='".substr($unique,0,16)."'");
					while ($data_mysql = mysql_fetch_array($dbp_mysql)) {
						if (is_dir($mysqldbpath.$data_mysql['Db'])) {
							unset($tmpquota);
							exec("/usr/bin/du -s ".$mysqldbpath.$data_mysql['Db'] , $tmpquota);
							$tmpquota = explode(" ",trim(eregi_replace("[[:space:]]+", " ", $tmpquota[0])));
							$mysqlquota = $mysqlquota + $tmpquota[0];
						}
					}
					if (!is_numeric($mysqlquota)) {
						$mysqlquota = 0;
					}

					webcp_log(3,0,"quota",$unique." mysql size = ".$mysqlquota,0,$echo);

					// get INBOX disk usage
					if (is_file($cfg['mail_spool']."/".$unique)) {
						exec("/usr/bin/du -s ".$cfg['mail_spool']."/".$unique ,$mailquota);
						$mailquota = explode(" ",trim(eregi_replace("[[:space:]]+", " ", $mailquota[0])));
						webcp_log(3,0,"quota",$unique." mail size = ".$mailquota[0],0,$echo);
					}

					// get imap disk usage
					if (is_dir($cfg['uwimapdir']."/".$unique)) {
						exec("/usr/bin/du -s ".$cfg['uwimapdir']."/".$unique."/" ,$imapquota);
						$imapquota = explode(" ",trim(eregi_replace("[[:space:]]+", " ", $imapquota[0])));
						webcp_log(3,0,"quota",$unique." imap folders size = ".$imapquota[0],0,$echo);
					}

					// total user disk usage = disk quota (files+imap) + mysql + INBOX
					$usertotal = $userquota[1] + $mysqlquota + $mailquota[0] + $imapquota[0];
					webcp_log(3,0,"quota",$unique." total size = ".$usertotal,0,$echo);

					mysql_select_db($cfg['dbname']);
					mysql_query("UPDATE users SET hd_used=".round($usertotal / 1024,2)." WHERE username='".$data_user['username']."' AND id='".$data['id']."'");

					// this calc the total disk space used outside of /home/domain/
					$quotatotal = $quotatotal + $mysqlquota + $mailquota[0] + $imapquota[0];
				}

				// calc the total disk space used; ie. space used in /home/domain plus elsewhere
				$quotatotal = $quotatotal + $hometotal;
				webcp_log(3,0,"quota",$data['id']." "." total size = ".$quotatotal,0,$echo);
				mysql_query("UPDATE domains SET hd_used=".round($quotatotal / 1024,2)." WHERE id='".$data['id']."'");
			}
		}
	}
}

function hd_quota_warn(&$data) {
	global $T, $cfg;

	$T['diskquotasubject'] = "Disk Quota Limit Exceeded";
	$T['userquotabody'] = "Please note that you have exceeded the disk quota limit set by your System Administrator. You are using %HDUSED%MB with only %HD%MB allocated. You will receive this email daily whenever your quota is exceeded. To make more space available, delete any items that you are no longer using or move them to your personal computer. Items in all your mailbox folders including the INBOX, Trash and Sent Items folders count against your size limits. You must empty the Trash folder after deleting items or the space will not be freed. You may check your disk quota from the PersonalCP page in WebCP. Please contact your System Administrator for more information.";
	$T['domainquotabody'] = "Please note that your domain: %DOMAIN% has exceeded the disk quota limit set by your System Administrator. You are using %HDUSED%MB with only %HD%MB allocated. You will receive this email daily whenever your quota is exceeded. To make more space available, delete any items that you are no longer using or move them to your personal computer. Items in all your users mailbox folders including the INBOX, Trash and Sent Items folders count against your size limits. They must empty the Trash folder after deleting items or the space will not be freed. You may check your disk quota from the DomainCP page in WebCP. Please contact your System Administrator for more information.";
	$T['resellerquotabody'] = "Please note that your reseller account: %NAME% has exceeded the disk quota limit set by your System Administrator. Your domains are using %HDUSED%MB with only %HD%MB allocated. You will receive this email daily whenever your quota is exceeded. To make more space available, delete any domains that you are no longer using. Items in all your users mailbox folders including the INBOX, Trash and Sent Items folders count against your size limits. They must empty the Trash folder after deleting items or the space will not be freed. You may check your disk quota from the ResellerCP page in WebCP. Please contact your System Administrator for more information.";

	if ($cfg['sendquotaemails']) {
		// Start User Quota check
		$dbp = mysql_query("SELECT users.username, users.hd, users.hd_used, domains.domain FROM users inner join domains ON users.id = domains.id WHERE users.type != 'demo' AND users.hd_used > users.hd AND users.hd != -1 AND users.suspend = 'false'");

		if (mysql_num_rows($dbp)) {
			while ($data = mysql_fetch_array($dbp)) {
				$search[] = "%HDUSED%";
				$search[] = "%HD%";
				$replace[] = $data['hd_used'];
				$replace[] = $data['hd'];
				$body = str_replace($search, $replace, $T['userquotabody']);
				mail($data["username"]."@".$data["domain"], $T['diskquotasubject'], $body, "From: noreply@".$cfg['sysname']);
				webcp_log(2,0,'quotawarn',"user disk quota warning sent to ".$data["username"],0);
			}
		}

		// Start domain quota check.
		$dbp = mysql_query("SELECT domains.email, domains.hd, domains.hd_used, domains.domain FROM domains WHERE domains.hd_used > domains.hd AND domains.hd != -1 AND domains.type = 'domain' AND domains.suspended = 'false'");

		if (mysql_num_rows($dbp)) {
			while ($data = mysql_fetch_array($dbp)) {
				$search[] = "%DOMAIN%";
				$search[] = "%HDUSED%";
				$search[] = "%HD%";
				$replace[] = $data['domain'];
				$replace[] = $data['hd_used'];
				$replace[] = $data['hd'];
				$body = str_replace($search, $replace, $T['domainquotabody']);
				mail($data["email"], $T['diskquotasubject'], $body, "From: noreply@".$cfg['sysname']);
				webcp_log(2,0,'quotawarn',"domain disk quota warning sent to ".$data['domain'],0);
			}
		}

		// Start reseller quota check.
		$dbp = mysql_query("SELECT resellers.name, resellers.email, sum(domains.hd_used) AS hdused, resellers.hd FROM resellers inner join domains on resellers.id = domains.owner WHERE resellers.hold = 'false' GROUP BY resellers.name");

		if (mysql_num_rows($dbp)) {
			while ($data = mysql_fetch_array($dbp)) {
				echo $data["hdused"]." > ".$data["hd"];
				if ($data["hdused"] > $data["hd"] && $data["hd"] != -1) {
					$search[] = "%NAME%";
					$search[] = "%HDUSED%";
					$search[] = "%HD%";
					$replace[] = $data['name'];
					$replace[] = $data['hdused'];
					$replace[] = $data['hd'];
					$body = str_replace($search, $replace, $T['resellerquotabody']);
					mail($data["email"], $T['diskquotasubject'], $body, "From: noreply@".$cfg['sysname']);
					webcp_log(2,0,'quotawarn',"reseller disk quota warning sent to ".$data['name'],0);
				}
			}
		}
	}
}

function hd_quota_set_linux(&$data) {
	global $cfg;

	$unique = get_property('unix user', $data['id'], $data['username']);

	if(!$unique)
		return;

	if ($data['hd'] == -1) {
		$hdquota = 0;
	} else {
		$hdquota = intval($data['hd'] * 1024);
	}

	if ($cfg['osversion'] == 'RedHat6.2') {
		$setq = $cfg['prog']['squota'].' -u '.$unique.' '.$cfg['devhd']." $hdquota $hdquota 0 0";
	} else {
		$setq = $cfg['prog']['squota'].' -u '.$unique." $hdquota $hdquota 0 0 ".$cfg['devhd'];
	}
	
	webcp_log(2,0,'quotaset',"user quota set: ".$setq,0);
	
	exec($setq);
}

function hd_quota_set_bsd(&$data) {
	global $cfg;

	$unique = get_property('unix user', $data['id'], $data['username']);

	/*
		To add a user quota on FreeBSD:
		edquota -e /home:0:99999999 -u user
		adds a soft/hard limit of 0/9999999 kb for the user 'user' on filesystem /home
	*/
	if ($data['hd'] == -1) {
		$hdquota = 0;
	} else {
		$hdquota = intval($data['hd'] * 1024);
	}
	
	$setq = $cfg['prog']['squota']." ".$cfg["webdir"].":0:$hdquota -u ".$unique;

	webcp_log(2,0,'quotaset',"user quota set: ".$setq,0);

	exec($setq);
}
?>